
#import "Common.h"

#import "Texture.h"

@implementation Texture

@synthesize glTextureName;
@synthesize width,height;
@synthesize imageData;

-(id) initWithName:(NSString*) fileName
{
	[super initWithName:fileName];
	
	UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:nil]];
	
//	int rr = [image retainCount];
	
	CGImageRef spriteImage;
	CGContextRef spriteContext;
	
	//NSLog(@"Texture name:%@\n",fileName);
	//spriteImage = [UIImage imageNamed:fileName].CGImage;
	//spriteImage = CGImageCreateWithPNGDataProvider(<#CGDataProviderRef source#>, <#const CGFloat [] decode#>, , <#CGColorRenderingIntent intent#>)
	//spriteImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:nil]].CGImage;
	
	spriteImage = image.CGImage;
	
	//int rc = [spriteImage retainCount];
	
	width = CGImageGetWidth(spriteImage);
	height = CGImageGetHeight(spriteImage);
	
	if(spriteImage) {
		imageData = (GLubyte *) malloc(width * height * 4);
		spriteContext = CGBitmapContextCreate(imageData, width, height, 8, width * 4, CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);

		CGContextDrawImage(spriteContext, CGRectMake(0.0, 0.0, (CGFloat)width, (CGFloat)height), spriteImage);
		
		CGContextRelease(spriteContext);
		
		glGenTextures(1, &glTextureName);
		glBindTexture(GL_TEXTURE_2D, glTextureName);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
		
		free(imageData);
		imageData = NULL;
		
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	}
	
	//[image release];
	
	return self;
}

-(void) dealloc
{
    if(glTextureName)
		glDeleteTextures(1, &glTextureName);
    
    [super dealloc];
}

@end
